package com.sicheng.algorithm.math;

/**
 * @author zsc
 * @version 1.0
 * @date 2021/9/15 14:53
 */
@SuppressWarnings("unused")
public class CustomMath {
    public static void main(String[] args) {
        System.out.println(power(1, -2));
    }

    public static double power(double base, int exponent) {
        if (Double.compare(base, 0) == 0) {
            if (exponent < 0) {
                System.out.println("0的负数次幂不存在");
                throw new RuntimeException();
            }
            //  0 的 n次幂返回0，  0的0次幂无数学意义
            return 0;
        }

        //  此后base非0
        if (Double.compare(base, 1) == 0)//如果base=1直接返回1，无需另行计算
            return 1;

        if (exponent > 0)
            return powerWithUnsignedExponent(base, exponent);
        if (exponent == 0)
            return 1;
        return 1 / powerWithUnsignedExponent(base, Math.abs(exponent));
    }

    // 无符号的base的exponent次幂
    private static double powerWithUnsignedExponent(double base, int exponent) {
        if (exponent <= 0) {
            throw new RuntimeException("exponent不允许为空");
        }
        double result = 1;
        for (int i = 0; i < exponent; i++) {
            result *= base;
        }
        return result;
    }

}
